package org.example.clouddemo.recommend.service.common.impl;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.clouddemo.bean.common.entity.Order;
import org.example.clouddemo.bean.common.entity.Product;
import org.example.clouddemo.bean.common.entity.User;
import org.example.clouddemo.recommend.feign.OrderFeignClient;
import org.example.clouddemo.recommend.feign.ProductFeignClient;
import org.example.clouddemo.recommend.service.common.RecommendService;
import org.example.common.response.ApiResult;
import org.example.common.utils.SecurityUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


/**
* 推荐表 服务实现类
*/
@Slf4j
@RequiredArgsConstructor
@Service // 业务逻辑层
public class RecommendServiceImpl implements RecommendService {

    private final ProductFeignClient productFeignClient;

    private final OrderFeignClient orderFeignClient;


    public List<Product> recommendProductListByUserId() {
        // 1、查询用户id
        User user = new User();
        Long userId = SecurityUtils.getUserId();
        user.setId(userId); //  通过token进行获取userId
        // 2、通过用户id查询对应的订单列表
        log.info("<UNK>userId<UNK>{}", userId);
        ApiResult<List<Order>> apiOrderResult = orderFeignClient.getByUserId(userId);
        if (CollectionUtils.isEmpty(apiOrderResult.getData()) || apiOrderResult.getData() == null) {
            log.warn("用户订单查询失败或订单为空: userId={}, result={}，将使用热门商品推荐", userId, apiOrderResult.getMsg());
            return getPopularRecommendations(userId);
        }
        List<Order> orders = apiOrderResult.getData();
        ApiResult<List<Product>> popularResult = productFeignClient.selectOrderByPriceDesc();
        if (popularResult.getData() == null || popularResult.getData().isEmpty()) {
            log.warn("商品查询失败，使用默认推荐");
            return getPopularRecommendations(userId);
        }
        List<Product> popularProducts = popularResult.getData();

        // 第二部分
        Map<Long, Product> productMap = popularProducts.stream()
                .collect(Collectors.toMap(Product::getId, p -> p));
        Set<Long> userProductIds = orders.stream()
                .map(Order::getProductId)
                .filter(Objects::nonNull)
                .distinct()
                .limit(3) // 最多考虑3个不同商品
                .collect(Collectors.toSet());
        // 优先推荐用户历史购买过的商品
        List<Product> historyRecommendations = userProductIds.stream()
                .map(productMap::get)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        // 如果历史推荐不足3个，从候选商品中补充
        if (historyRecommendations.size() < 3) {
            int needCount = 3 - historyRecommendations.size();
            List<Product> supplementaryProducts = popularProducts.stream()
                    .filter(p -> !userProductIds.contains(p.getId()))
                    .limit(needCount)
                    .collect(Collectors.toList());
            historyRecommendations.addAll(supplementaryProducts);
        }

        return historyRecommendations;

    }

    private List<Product> getPopularRecommendations(Long userId) {
        ApiResult<List<Product>> result = productFeignClient.selectOrderByPriceDesc();
        if (result.isSuccess() && !CollectionUtils.isEmpty(result.getData())) {
            return result.getData().stream()
                    .limit(3)
                    .collect(Collectors.toList());
        }
        log.warn("高价商品推荐失败: userId={}, result.data={}", userId, result.getData());
        return Collections.emptyList();
    }

}